package main

import (
	"fmt"
	"log"
	"sync/atomic"
	"time"

	"gitee.com/fcsvr/fc/fclog"
	"github.com/go-resty/resty/v2"
	"github.com/tidwall/gjson"
)

func Login() {
	// 创建客户端并设置 BaseAuth
	G_Client = resty.New().SetBasicAuth(G_User, G_Pswd)

	// 发起带有 BaseAuth 的 POST 请求
	resp, err := G_Client.R().SetHeader("Content-Type", "application/json").Post("https://api.worldquantbrain.com/authentication")

	if err != nil {
		log.Fatalf("Request failed: %v", err)
	}

	// 解析响应
	//var result struct {
	//Message string `json:"message"`
	//}
	fclog.Info(string(resp.Body()))
	//if err := json.Unmarshal(resp.Body(), &result); err != nil {
	//log.Fatalf("Unmarshal failed: %v", err)
	//}
	result := gjson.Get(string(resp.Body()), "user.id")
	fclog.Info("Response Status Code:%v", resp.StatusCode())
	fclog.Info("Response User:%v", result)
	fclog.Info("Response Body:%v", resp.String())
}

func Test() {
	for G_Count < G_AlphaLen-1 {
		atomic.AddInt32(&G_Count, 1)
		fclog.Info("G_Count: %d", G_Count)
		time.Sleep(time.Second)
	}
	G_WaitGroup.Done()
}

func Run() {
}

func Tick() {
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	GetActiveAlphaPnlFromFile()
	//go GetActiveAlphaPnl("USA")

	for now := range ticker.C {
		if now.Minute() == 0 && now.Second() == 0 {
			year, month, day, hour := now.Year(), now.Month(), now.Day(), now.Hour()
			fclog.Info("Tick %v-%v-%v-%v", year, month, day, hour)
			month0 := month - 1
			day0 := day - 3
			if day0 < 1 {
				day0 = 1
			}
			if month0 < 1 {
				month0 = 1
				day0 = 1
			}
			startDate := fmt.Sprintf("%d-%d-%d", year, month0, day0)
			endDate := fmt.Sprintf("%d-%d-%d", year, month0, day)
			//SetHiddenAlphasByFitness(startDate, endDate, "USA")
			//SetHiddenAlphasByCount(startDate, endDate, "USA")
			fclog.Debug("Tick %v, %v", startDate, endDate)
			//RefreshAlphaByColor("USA", "BLUE")
			if hour == 1 {
				fclog.Info("Hour = 0")
				//CheckSubmitAlphas(startDate, endDate, 1, 1.25, "USA")
				//GetActiveAlphaPnl("USA")
				//RefreshAlphaByColor("USA", "BLUE")
			}
		}
	}
}

func main() {
	Init()
	Login()
	if G_Flag == 1 {
		go Tick()
		fclog.Info("Alpha Thread = %d", G_SimulateNum)
		ConstructAlphaExpressFromFile(G_SimulateFile)
		fclog.Debug("Alpha Run 1")
		SimulatePool()
		fclog.Debug("Alpha Run 2")
	} else if G_Flag == 2 {
		fclog.Info("Super Thread = %d", G_SimulateNum)
		ConstructSuperFromFile(G_SimulateFile)
		fclog.Debug("Super Run 1")
		SimulateSuperPool()
		fclog.Debug("Super Run 2")
	} else {
		Tool()
	}
}
